package k3;


public class DynamicArray<A> {
	private static final int minSize=1;
	private A[] array;
	private int num;
	private int size;
	DynamicArray(int n){
		if(n<1)n=1;
		array=(A[]) new Object[n];
		size=n;
		num=0;
	}
	
	DynamicArray(){
		this(0);
	}
	public void add(A number, int index){
		if(num==size){
			moveArray(size*2);
		}
		num++;
		for(int i=num-1;i>index;i--)array[i]=array[i-1];
		array[index]=number;
	}
	public void add(A number){
		add(number,num);
	}
	public A get(int index){
		if(index>num-1)throw new IndexOutOfBoundsException();
		return array[index];
	}
	public void set(int index,A number){
		if(index>num-1)throw new IndexOutOfBoundsException();
		array[index]=number;
	}
	public void delete(int index){
		if(index>num-1)throw new IndexOutOfBoundsException();
		for(int i=index;i<num-1;i++)array[i]=array[i+1];
		num--;
		if(num<=size/4 && size>minSize)moveArray(size/2);
	}
	public A removeLast(){
		A element=get(num-1);
		delete(num-1);
		return element;
	}
	public int length(){
		return num;
	}
	private void moveArray(int newSize){
		A[] tempArray=(A[]) new Object[newSize];
		for(int i=0;i<num;i++)tempArray[i]=array[i];
		array=tempArray;
		size=newSize;
	}
}
